# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

library(gplots)
library(Hmisc)
library(optparse)
library(ropls)
library(magrittr)
library(ComplexHeatmap)
library(circlize)
library(tidyverse)

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

diffData <- read_csv("../../potential/Markers.csv")

if (nrow(diffData) == 0) {
  quit(status = 0)
}

diffNames <- diffData %>%
  .$Metabolite

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

classNotes <- sampleInfo %>%
  .$ClassNote %>%
  unique()

groupNames <- c(classNotes, paste0(classNotes, collapse = "_vs_"))

orignalData <- read.csv(opt$i, header = T, stringsAsFactors = F) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  filter(Metabolite %in% diffNames) %>%
  as.data.frame()

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
  set_colnames(c("arg", "value")) %>%
  column_to_rownames("arg")

corP <- configData["cor.p", "value"] %>%
  as.numeric()
cor <- configData["cor.coe", "value"] %>%
  as.numeric()

print(groupNames)

for (groupName in groupNames) {
  groups <- unlist(strsplit(groupName, "_vs_"))
  sampleIds <- sampleInfo %>%
    filter(ClassNote %in% groups) %>%
    .$SampleID

  parent <- str_replace_all(groupName, "_vs_", "_and_")
  createWhenNoExist(parent)
  fileName <- paste0(parent, "/Intra_Correlation_Heatmap.pdf")
  corData <- read_csv(str_c(parent, "/Intra_r_Matrix.csv"))
  if (nrow(corData) < 2) {
    next
  }

  pData <- read_csv(str_c(parent, "/Intra_P_Matrix.csv")) %>%
    column_to_rownames("X1") %>%
    as.matrix()

  colors <- rev(colorRampPalette(RColorBrewer::brewer.pal(10, "RdBu"))(256))

  plotData <- corData %>%
    column_to_rownames("X1") %>%
    as.matrix()

  rowNum <- nrow(plotData)
  colNum <- ncol(plotData)

  row_names = rownames(plotData)
  col_names = colnames(plotData)
  max_row_chr_num = max(nchar(row_names))
  max_col_chr_num = max(nchar(col_names))

  height <- max(2 + (rowNum - 10) * 0.1, 2) + 1 / 4 * max_col_chr_num
  height
  width <- max(2 + (colNum - 10) * 0.1, 2) + 1 / 4 * max_row_chr_num
  width

  maxLength <- max(c(height, width))

  pdf(fileName, width = maxLength, height = maxLength)

  firstValue <- plotData[1, 1]
  b <- all(plotData == firstValue)
  if (b) {
    next
  }

  eachHeight <- 1 / rowNum

  htList <- Heatmap(plotData, col = colors, show_column_names = T, cluster_rows = T, cluster_columns = T,
                    name = "", row_names_gp = gpar(fontsize = 6, fontfamily = "Times"), show_row_names = T, show_heatmap_legend = F,
                    column_names_gp = gpar(fontsize = 6, fontfamily = "Times"), cell_fun = function(j, i, x, y, width, height, fill) {
      value <- pData[i, j]
      str <- if (value < 0.01) {
        "+"
      }else if (value < 0.05) {
        "*"
      }else ""
      top <- if (str == "*") {
        y - unit(eachHeight * 0.12, "npc")
      }else y
      grid.text(str, x, top, gp = gpar(fontsize = 9), hjust = 0.5, vjust = 0.5, just = "center")
    })

  rLgd <- Legend(col_fun = colorRamp2(seq(-1, 1, length.out = 256), colors), at = seq(-1, 1, 0.5), title = "",
                 title_gp = gpar(fontsize = 12, fontfamily = "Times"), grid_height = unit(7.5, "mm"),
                 labels_gp = gpar(fontsize = 12, fontfamily = "Times"))

  pLegend <- Legend(pch = c("+", "*"), type = "points", labels = c("p<0.01", "0.01<=p<0.05"), title = "",
                    labels_gp = gpar(fontsize = 9, fontfamily = "Times"), title_gp = gpar(fontsize = 12, fontfamily = "Times"),
                    ncol = 1, grid_height = unit(5, "mm"),
  )
  pd <- packLegend(list = list(rLgd, pLegend), row_gap = unit(0.5, "cm"))

  draw(htList, heatmap_legend_side = "right", annotation_legend_side = "right",
       padding = unit(c(0.5, 0.5, 0.5, 0.5), "cm"), annotation_legend_list = pd
  )
  dev.off()
}



